<?php
	session_start();
	$userId = $_SESSION['userId'];
	$sessionId = $_POST['selectWS'];

	$con = mysql_connect("localhost", "group5", "group5");//change this when moving to/from wamp
    if(!$con)
    {
		echo "Connection failed!";
        exit;
    }
	
	mysql_select_db("group5");//this will need to be changed for the group5 database
	
	$checkInsert = "select * from USER_WORKSHOP where workshopSessionId = $sessionId and userId = $userId";
	$dupCourse = FALSE;
	$insertResult = mysql_query($checkInsert);
	while ($insertRow = mysql_fetch_row($insertResult))
	{
		$insertSession = $insertRow[0];
		$insertUser = $insertRow[1];
		if ($sessionId == $insertSession AND $userId == $insertUser)
		{
			$dupCourse = TRUE;	
		}//end if
	}//end while
	
	if ($dupCourse == TRUE)
	{
		header("Location:registerShopPage.php?regShopMsg=User already registered for session");
	}//end if
	else
	{
		$insertQuery = "insert into USER_WORKSHOP (workshopSessionId, userId) values ($sessionId, $userId)";
		mysql_query($insertQuery);
		
		//User info for email
		$userInfo = "select * from USERS where userId = $userId";
		$userResult = mysql_query($userInfo);
		while($userRow = mysql_fetch_row($userResult))
		{
			$fName = $userRow[1];
			$lName = $userRow[2];
			$email = $userRow[3];
		}
		
		//Workshop info for email
		$wsInfo = "select * from WORKSHOP as WS join WORKSHOP_SESSIONS as WSS on WSS.workshopId = WS.workshopId where WSS.workshopSessionId = $sessionId";
		$wsResult = mysql_query($wsInfo);
		while($wsRow = mysql_fetch_row($wsResult))
		{
			$title = $wsRow[1];
			$time = $wsRow[5];
			$day = $wsRow[6];
		}
		
		$to = $email;
		$subject = 'CIRT Workshop Signup';
		$message = "Dear $safeFName,\r\rThank you for use CIRT's website to register for the workshop '$title' on $day at $time.\r\rThank you, and have a wonderful day,\rGroup5";
		$headers = 'From: webmaster@fake.com'. '\r\n' . 'Reply-to: webmaster@fake.com' . '\r\n' . 'X-Mailer: PHP/' . phpversion();
		mail($to, $subject, $message);

		header("Location:registerShopPage.php?regShopMsg=Workshop added, please check your email.");
	}//end else
	
	mysql_close($con);
?>